// dh-income_records 云对象 - 收入记录管理
const db = uniCloud.database();
const _ = db.command;
const { 
	autoMountHospitalId, 
	softDelete, 
	batchSoftDelete, 
	getUserById, 
	getUserList, 
	getMainRole,
	// 权限工具函数 - 从permission-utils.js导入
	INCOME_RECORD_PERMISSIONS,
	checkIncomeRecordViewPermission,
	checkIncomeRecordEditPermission,
	checkIncomeRecordDeletePermission,
	checkIncomeRecordApprovePermission,
	buildIncomeRecordQueryConditions,
	createTemporaryAuth,
	revokeTemporaryAuth,
	getUserTemporaryAuths,
	logPermissionAction,
	getUserAccessibleResources,
	hasAdminPermission
} = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-income_records] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

/**
 * 解析JWT Token获取用户信息
 */
function parseToken(token) {
	if (!token) return null;
	try {
		const parts = token.split('.');
		if (parts.length !== 3) return null;
		const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString());
		return payload;
	} catch (error) {
		console.error('[dh-income_records] Token解析失败:', error);
		return null;
	}
}

/**
 * 获取角色的中文名称
 */
function getRoleText(role) {
	const roleMap = {
		'admin': '超级管理员',
		'manager': '管理员',
		'director': '院长',
		'doctor': '医生',
		'nurse': '护士',
		'administrative': '行政',
		'finance': '财务',
		'purchaser': '采购员'
	};
	return roleMap[role] || role || '员工';
}

/**
 * 为单个收入记录附加员工信息
 */
async function enrichIncomeRecordInfo(record) {
	if (!record || !record.user_id) return record;

	try {
		// 使用统一的用户查询工具获取用户信息（自动解密）
		const userInfo = await getUserById(record.user_id, 'full', false, true);
		
		if (userInfo) {
			record.staff_name = userInfo.realName || userInfo.displayName || '未知';
			
			// 使用 getMainRole 获取优先级最高的角色（正确处理多角色用户）
			const mainRole = getMainRole(userInfo) || 'user';
			record.staff_role = mainRole;
			record.staff_role_text = getRoleText(mainRole);
		}
	} catch (error) {
		console.error('[dh-income_records] 获取员工信息失败:', error);
		record.staff_name = '未知';
		record.staff_role_text = '员工';
	}

	return record;
}

/**
 * 为收入记录列表批量附加员工信息
 */
async function enrichIncomeRecordsList(records) {
	if (!Array.isArray(records) || records.length === 0) {
		return records;
	}

	// 收集所有员工ID
	const userIds = [...new Set(records.map(r => r.user_id).filter(Boolean))];

	if (userIds.length === 0) return records;

	try {
		// 批量获取用户信息（使用统一的用户查询工具）
		const allUsers = await getUserList({
			format: 'full',
			limit: 1000,
			decryptSensitiveInfo: true,
			allowPatients: true
		});
		
		// 过滤出需要的用户
		const userRes = {
			data: allUsers.filter(user => userIds.includes(user._id))
		};

		// 构建用户映射
		const userMap = {};
		userRes.data.forEach(user => {
			// 使用 getMainRole 获取优先级最高的角色（正确处理多角色用户）
			const mainRole = getMainRole(user) || 'user';
			
			userMap[user._id] = {
				name: user.realName || user.displayName || '未知',
				role: mainRole,
				role_text: getRoleText(mainRole)
			};
		});

		// 附加信息到收入记录
		records.forEach(record => {
			if (record.user_id && userMap[record.user_id]) {
				record.staff_name = userMap[record.user_id].name;
				record.staff_role = userMap[record.user_id].role;
				record.staff_role_text = userMap[record.user_id].role_text;
			} else {
				record.staff_name = '未知';
				record.staff_role_text = '员工';
			}
		});
	} catch (error) {
		console.error('[dh-income_records] 批量获取员工信息失败:', error);
	}

	return records;
}

module.exports = {
	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const uniIdToken = this.getUniIdToken();
		console.log(`[dh-income_records] 调用方法: ${methodName}, 用户ID: ${uniIdToken?.uid}`);

		const writeMethods = ['create', 'update', 'delete', 'batch', 'approve', 'reject'];
		if (methodName && writeMethods.some(method => methodName.toLowerCase().includes(method))) {
			if (!uniIdToken || !uniIdToken.uid) {
				throw new Error('401|未授权的访问');
			}
		}

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	/**
	 * 根据ID查询收入记录（自动附加员工信息，检查权限）
	 */
	async getIncomeRecordById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '收入记录ID不能为空');
			}

			// 获取当前用户ID
			const uniIdToken = this.getUniIdToken();
			const currentUserId = uniIdToken?.uid;
			
			if (!currentUserId) {
				return formatResponse(401, null, '未授权的访问');
			}

			// 获取收入记录
			const res = await db.collection('dh-income_records').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '收入记录不存在');
			}
			
			const recordData = res.data[0];
			
			// 使用权限工具检查查看权限
			const permissionResult = await checkIncomeRecordViewPermission(
				currentUserId, 
				recordData.user_id
			);
			
			if (!permissionResult.hasPermission) {
				// 记录权限检查日志
				await logPermissionAction(currentUserId, 'check_view_permission', {
					recordId: id,
					hasPermission: false,
					reason: permissionResult.reason
				});
				
				return formatResponse(403, null, '无权查看此收入记录');
			}
			
			// 附加员工信息
			const enrichedData = await enrichIncomeRecordInfo(recordData);
			
			// 记录权限检查日志
			await logPermissionAction(currentUserId, 'check_view_permission', {
				recordId: id,
				hasPermission: true,
				reason: permissionResult.reason
			});
			
			return formatResponse(200, enrichedData);
		} catch (error) {
			return formatError(error, '获取收入记录失败');
		}
	},

	/**
	 * 获取收入记录列表（自动关联员工信息，根据权限过滤）
	 */
	async listIncomeRecords(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
			skip = parseInt(skip) || 0;
			limit = parseInt(limit) || 20;
			
			// 获取当前用户ID
			const uniIdToken = this.getUniIdToken();
			const currentUserId = uniIdToken?.uid;
			
			if (!currentUserId) {
				return formatResponse(401, null, '未授权的访问');
			}
			
			// 使用权限工具构建查询条件
			let finalQuery = await buildIncomeRecordQueryConditions(currentUserId, query);
			
			// 默认不显示已删除记录
			finalQuery.is_deleted = false;
			
			// 查询收入记录
			const res = await db.collection('dh-income_records')
				.where(finalQuery)
				.skip(skip)
				.limit(limit)
				.orderBy('create_time', 'desc')
				.get();
			
			// 批量附加员工信息
			let enrichedData = await enrichIncomeRecordsList(res.data);
			
			// 记录权限检查日志
			await logPermissionAction(currentUserId, 'list_income_records', {
				queryConditions: finalQuery,
				resultCount: enrichedData.length
			});
			
			return formatResponse(200, enrichedData, 'success', { count: enrichedData.length });
		} catch (error) {
			return formatError(error, '获取收入记录列表失败');
		}
	},

	/**
	 * 创建收入记录
	 */
	async createIncomeRecord(data) {
		try {
			// 获取当前用户ID
			const uniIdToken = this.getUniIdToken();
			const currentUserId = uniIdToken?.uid;
			
			if (!currentUserId) {
				return formatResponse(401, null, '未授权的访问');
			}

			if (!data.user_id || !data.year_month) {
				return formatResponse(400, null, '员工ID和月份不能为空');
			}

			// 使用权限工具检查创建权限
			const permissionResult = await checkIncomeRecordEditPermission(
				currentUserId, 
				data.user_id
			);
			
			if (!permissionResult.hasPermission) {
				// 记录权限检查日志
				await logPermissionAction(currentUserId, 'check_create_permission', {
					targetUserId: data.user_id,
					hasPermission: false,
					reason: permissionResult.reason
				});
				
				return formatResponse(403, null, '无权创建此收入记录');
			}

			let incomeData = {
				user_id: data.user_id,
				year_month: data.year_month,
				base_salary: parseFloat(data.base_salary) || 0,
				commission_amount: parseFloat(data.commission_amount) || 0,
				bonus_amount: parseFloat(data.bonus_amount) || 0,
				deduction_amount: parseFloat(data.deduction_amount) || 0,
				dividend_amount: parseFloat(data.dividend_amount) || 0,
				total_income: parseFloat(data.total_income) || 0,
				remarks: data.remarks || '',
				created_by: currentUserId,
				status: parseInt(data.status) || 1,  // 1-待审批，2-已审批，3-已发放，4-已拒绝
				is_deleted: false,  // 软删除字段，默认未删除
				create_time: Date.now(),
				update_time: Date.now()
			};

			// 🏥 自动挂载医院ID（单一医院系统特性）
			incomeData = await autoMountHospitalId(incomeData);

			const res = await db.collection('dh-income_records').add(incomeData);
			
			// 记录权限操作日志
			await logPermissionAction(currentUserId, 'create_income_record', {
				recordId: res.id,
				targetUserId: data.user_id
			});
			
			return formatResponse(201, { _id: res.id }, '收入记录创建成功');
		} catch (error) {
			return formatError(error, '创建收入记录失败');
		}
	},

	/**
	 * 更新收入记录
	 */
	async updateIncomeRecord(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '收入记录ID不能为空');
			}

			// 获取当前用户ID
			const uniIdToken = this.getUniIdToken();
			const currentUserId = uniIdToken?.uid;
			
			if (!currentUserId) {
				return formatResponse(401, null, '未授权的访问');
			}

			// 获取收入记录
			const res = await db.collection('dh-income_records').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '收入记录不存在');
			}
			
			const recordData = res.data[0];
			
			// 使用权限工具检查编辑权限
			const permissionResult = await checkIncomeRecordEditPermission(
				currentUserId, 
				recordData.user_id
			);
			
			if (!permissionResult.hasPermission) {
				// 记录权限检查日志
				await logPermissionAction(currentUserId, 'check_edit_permission', {
					recordId: id,
					hasPermission: false,
					reason: permissionResult.reason
				});
				
				return formatResponse(403, null, '无权编辑此收入记录');
			}

			const updateData = {
				...data,
				update_time: Date.now()
			};

			await db.collection('dh-income_records').doc(id).update(updateData);
			
			// 记录权限操作日志
			await logPermissionAction(currentUserId, 'update_income_record', {
				recordId: id,
				targetUserId: recordData.user_id
			});
			
			return formatResponse(200, null, '收入记录更新成功');
		} catch (error) {
			return formatError(error, '更新收入记录失败');
		}
	},

	/**
	 * 审批通过收入记录
	 */
	async approveIncomeRecord(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '收入记录ID不能为空');
			}

			// 获取当前用户ID
			const uniIdToken = this.getUniIdToken();
			const currentUserId = uniIdToken?.uid;
			
			if (!currentUserId) {
				return formatResponse(401, null, '未授权的访问');
			}

			// 获取收入记录
			const res = await db.collection('dh-income_records').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '收入记录不存在');
			}
			
			const recordData = res.data[0];
			
			// 使用权限工具检查审批权限
			const permissionResult = await checkIncomeRecordApprovePermission(
				currentUserId, 
				recordData.user_id
			);
			
			if (!permissionResult.hasPermission) {
				// 记录权限检查日志
				await logPermissionAction(currentUserId, 'check_approve_permission', {
					recordId: id,
					hasPermission: false,
					reason: permissionResult.reason
				});
				
				return formatResponse(403, null, '无权审批此收入记录');
			}

			const updateData = {
				status: 2,  // 2-已审批
				approved_by: currentUserId,
				approved_time: Date.now(),
				update_time: Date.now()
			};

			await db.collection('dh-income_records').doc(id).update(updateData);
			
			// 记录权限操作日志
			await logPermissionAction(currentUserId, 'approve_income_record', {
				recordId: id,
				targetUserId: recordData.user_id
			});
			
			return formatResponse(200, null, '审批通过');
		} catch (error) {
			return formatError(error, '审批失败');
		}
	},

	/**
	 * 拒绝收入记录
	 */
	async rejectIncomeRecord(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '收入记录ID不能为空');
			}

			// 获取当前用户ID
			const uniIdToken = this.getUniIdToken();
			const currentUserId = uniIdToken?.uid;
			
			if (!currentUserId) {
				return formatResponse(401, null, '未授权的访问');
			}

			// 获取收入记录
			const res = await db.collection('dh-income_records').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '收入记录不存在');
			}
			
			const recordData = res.data[0];
			
			// 使用权限工具检查审批权限
			const permissionResult = await checkIncomeRecordApprovePermission(
				currentUserId, 
				recordData.user_id
			);
			
			if (!permissionResult.hasPermission) {
				// 记录权限检查日志
				await logPermissionAction(currentUserId, 'check_approve_permission', {
					recordId: id,
					hasPermission: false,
					reason: permissionResult.reason
				});
				
				return formatResponse(403, null, '无权拒绝此收入记录');
			}

			const updateData = {
				status: 4,  // 4-已拒绝
				rejection_reason: reason || '未填写原因',
				approved_by: currentUserId,
				approved_time: Date.now(),
				update_time: Date.now()
			};

			await db.collection('dh-income_records').doc(id).update(updateData);
			
			// 记录权限操作日志
			await logPermissionAction(currentUserId, 'reject_income_record', {
				recordId: id,
				targetUserId: recordData.user_id,
				reason
			});
			
			return formatResponse(200, null, '已拒绝');
		} catch (error) {
			return formatError(error, '拒绝失败');
		}
	},

	/**
	 * 删除收入记录
	 */
	async deleteIncomeRecord(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '收入记录ID不能为空');
			}

			// 获取当前用户ID
			const uniIdToken = this.getUniIdToken();
			const currentUserId = uniIdToken?.uid;
			
			if (!currentUserId) {
				return formatResponse(401, null, '未授权的访问');
			}

			// 获取收入记录
			const res = await db.collection('dh-income_records').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '收入记录不存在');
			}
			
			const recordData = res.data[0];
			
			// 使用权限工具检查删除权限
			const permissionResult = await checkIncomeRecordDeletePermission(
				currentUserId, 
				recordData.user_id
			);
			
			if (!permissionResult.hasPermission) {
				// 记录权限检查日志
				await logPermissionAction(currentUserId, 'check_delete_permission', {
					recordId: id,
					hasPermission: false,
					reason: permissionResult.reason
				});
				
				return formatResponse(403, null, '无权删除此收入记录');
			}

			// 软删除
			const result = await softDelete('dh-income_records', id, currentUserId, reason);
			
			// 记录权限操作日志
			await logPermissionAction(currentUserId, 'delete_income_record', {
				recordId: id,
				targetUserId: recordData.user_id
			});
			
			if (result.code === 200) {
				return formatResponse(200, null, '收入记录已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除收入记录失败');
		}
	},

	/**
	 * 批量更新收入记录
	 */
	async batchUpdateIncomeRecords(updates) {
		try {
			if (!Array.isArray(updates) || updates.length === 0) {
				return formatResponse(400, null, '更新数据不能为空');
			}

			// 获取当前用户ID
			const uniIdToken = this.getUniIdToken();
			const currentUserId = uniIdToken?.uid;
			
			if (!currentUserId) {
				return formatResponse(401, null, '未授权的访问');
			}

			// 获取所有收入记录
			const recordIds = updates.map(item => item._id);
			const recordsRes = await db.collection('dh-income_records').where({
				_id: db.command.in(recordIds)
			}).get();
			
			if (recordsRes.data.length === 0) {
				return formatResponse(404, null, '未找到指定的收入记录');
			}
			
			// 检查每条记录的编辑权限
			const unauthorizedIds = [];
			for (const record of recordsRes.data) {
				const permissionResult = await checkIncomeRecordEditPermission(
					currentUserId, 
					record.user_id
				);
				
				if (!permissionResult.hasPermission) {
					unauthorizedIds.push(record._id);
					
					// 记录权限检查日志
					await logPermissionAction(currentUserId, 'check_edit_permission', {
						recordId: record._id,
						hasPermission: false,
						reason: permissionResult.reason
					});
				}
			}
			
			if (unauthorizedIds.length > 0) {
				return formatResponse(403, null, `无权编辑以下收入记录: ${unauthorizedIds.join(', ')}`);
			}

			// 批量更新
			const promises = updates.map(item =>
				db.collection('dh-income_records').doc(item._id).update({
					...item,
					update_time: Date.now()
				})
			);

			await Promise.all(promises);
			
			// 记录权限操作日志
			for (const record of recordsRes.data) {
				await logPermissionAction(currentUserId, 'batch_update_income_records', {
					recordId: record._id,
					targetUserId: record.user_id
				});
			}
			
			return formatResponse(200, null, `批量更新${updates.length}条记录成功`);
		} catch (error) {
			return formatError(error, '批量更新失败');
		}
	},

	/**
	 * 批量删除收入记录
	 */
	async batchDeleteIncomeRecords(ids, reason = '') {
		try {
			if (!Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, 'ID列表不能为空');
			}

			// 获取当前用户ID
			const uniIdToken = this.getUniIdToken();
			const currentUserId = uniIdToken?.uid;
			
			if (!currentUserId) {
				return formatResponse(401, null, '未授权的访问');
			}

			// 获取所有收入记录
			const recordsRes = await db.collection('dh-income_records').where({
				_id: db.command.in(ids)
			}).get();
			
			if (recordsRes.data.length === 0) {
				return formatResponse(404, null, '未找到指定的收入记录');
			}
			
			// 检查每条记录的删除权限
			const unauthorizedIds = [];
			for (const record of recordsRes.data) {
				const permissionResult = await checkIncomeRecordDeletePermission(
					currentUserId, 
					record.user_id
				);
				
				if (!permissionResult.hasPermission) {
					unauthorizedIds.push(record._id);
					
					// 记录权限检查日志
					await logPermissionAction(currentUserId, 'check_delete_permission', {
						recordId: record._id,
						hasPermission: false,
						reason: permissionResult.reason
					});
				}
			}
			
			if (unauthorizedIds.length > 0) {
				return formatResponse(403, null, `无权删除以下收入记录: ${unauthorizedIds.join(', ')}`);
			}

			// 批量软删除
			const result = await batchSoftDelete('dh-income_records', ids, currentUserId, reason);
			
			// 记录权限操作日志
			for (const record of recordsRes.data) {
				await logPermissionAction(currentUserId, 'batch_delete_income_records', {
					recordId: record._id,
					targetUserId: record.user_id
				});
			}
			
			return formatResponse(result.code, result.data, result.message);
		} catch (error) {
			return formatError(error, '批量删除失败');
		}
	}
};
